package com.jussi.android.threadsocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

public class ServerThread implements Runnable{
	Socket socket;
	InputStream inputStream;
	OutputStream outputStream;
	BufferedReader reader;
	public ServerThread(Socket socket) throws IOException {
		this.socket = socket;
		inputStream = socket.getInputStream();
		reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		String string;
		while( (string=readData()) != null ) {
			for(Socket s: MyServer.list) {
				try {
					outputStream = s.getOutputStream();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				PrintStream printStream = new PrintStream(outputStream);
				printStream.println(socket.getInetAddress() + ":" + string);
			}
		}
	}
	
	private String readData() {
		try {
			return reader.readLine();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			MyServer.list.remove(socket);
			return null;
		}
	}
	
}
